import {
  Organization,
  OrganizationFilter,
  CreateOrganizationRequest,
  UpdateOrganizationRequest,
  PaginatedResponse,
  ApiResponse,
} from '@/types';

// 组织服务类
class OrganizationService {
  private baseUrl = '/api/organizations';

  // 获取组织列表
  async getOrganizations(params: OrganizationFilter = {}): Promise<PaginatedResponse<Organization>> {
    const searchParams = new URLSearchParams();
    
    Object.entries(params).forEach(([key, value]) => {
      if (value !== undefined && value !== null && value !== '') {
        searchParams.append(key, String(value));
      }
    });

    const response = await fetch(`${this.baseUrl}?${searchParams.toString()}`);
    if (!response.ok) {
      throw new Error(`Failed to fetch organizations: ${response.statusText}`);
    }
    
    return response.json();
  }

  // 获取单个组织详情
  async getOrganization(id: string): Promise<ApiResponse<Organization>> {
    const response = await fetch(`${this.baseUrl}/${id}`);
    if (!response.ok) {
      throw new Error(`Failed to fetch organization: ${response.statusText}`);
    }
    
    return response.json();
  }

  // 创建组织
  async createOrganization(data: CreateOrganizationRequest): Promise<ApiResponse<Organization>> {
    const response = await fetch(this.baseUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data),
    });
    
    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}));
      throw new Error(errorData.message || `Failed to create organization: ${response.statusText}`);
    }
    
    return response.json();
  }

  // 更新组织
  async updateOrganization(id: string, data: UpdateOrganizationRequest): Promise<ApiResponse<Organization>> {
    const response = await fetch(`${this.baseUrl}/${id}`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data),
    });
    
    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}));
      throw new Error(errorData.message || `Failed to update organization: ${response.statusText}`);
    }
    
    return response.json();
  }

  // 删除组织
  async deleteOrganization(id: string): Promise<ApiResponse<void>> {
    const response = await fetch(`${this.baseUrl}/${id}`, {
      method: 'DELETE',
    });
    
    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}));
      throw new Error(errorData.message || `Failed to delete organization: ${response.statusText}`);
    }
    
    return response.json();
  }

  // 获取组织树形结构
  async getOrganizationTree(tenantId?: string): Promise<ApiResponse<Organization[]>> {
    const searchParams = new URLSearchParams();
    if (tenantId) {
      searchParams.append('tenantId', tenantId);
    }
    searchParams.append('tree', 'true');

    const response = await fetch(`${this.baseUrl}/tree?${searchParams.toString()}`);
    if (!response.ok) {
      throw new Error(`Failed to fetch organization tree: ${response.statusText}`);
    }
    
    return response.json();
  }

  // 移动组织
  async moveOrganization(id: string, newParentId: string | null): Promise<ApiResponse<Organization>> {
    const response = await fetch(`${this.baseUrl}/${id}/move`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ newParentId }),
    });
    
    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}));
      throw new Error(errorData.message || `Failed to move organization: ${response.statusText}`);
    }
    
    return response.json();
  }

  // 获取组织成员
  async getOrganizationMembers(id: string): Promise<ApiResponse<any[]>> {
    const response = await fetch(`${this.baseUrl}/${id}/members`);
    if (!response.ok) {
      throw new Error(`Failed to fetch organization members: ${response.statusText}`);
    }
    
    return response.json();
  }

  // 添加组织成员
  async addOrganizationMember(organizationId: string, userId: string): Promise<ApiResponse<void>> {
    const response = await fetch(`${this.baseUrl}/${organizationId}/members`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ userId }),
    });
    
    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}));
      throw new Error(errorData.message || `Failed to add organization member: ${response.statusText}`);
    }
    
    return response.json();
  }

  // 移除组织成员
  async removeOrganizationMember(organizationId: string, userId: string): Promise<ApiResponse<void>> {
    const response = await fetch(`${this.baseUrl}/${organizationId}/members/${userId}`, {
      method: 'DELETE',
    });
    
    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}));
      throw new Error(errorData.message || `Failed to remove organization member: ${response.statusText}`);
    }
    
    return response.json();
  }

  // 获取组织统计信息
  async getOrganizationStats(id: string): Promise<ApiResponse<any>> {
    const response = await fetch(`${this.baseUrl}/${id}/stats`);
    if (!response.ok) {
      throw new Error(`Failed to fetch organization stats: ${response.statusText}`);
    }
    
    return response.json();
  }

  // 启用/禁用组织
  async toggleOrganizationStatus(id: string): Promise<ApiResponse<Organization>> {
    const response = await fetch(`${this.baseUrl}/${id}/toggle-status`, {
      method: 'POST',
    });
    
    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}));
      throw new Error(errorData.message || `Failed to toggle organization status: ${response.statusText}`);
    }
    
    return response.json();
  }

  // 复制组织结构
  async copyOrganization(sourceId: string, targetParentId?: string, name?: string): Promise<ApiResponse<Organization>> {
    const response = await fetch(`${this.baseUrl}/${sourceId}/copy`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ targetParentId, name }),
    });
    
    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}));
      throw new Error(errorData.message || `Failed to copy organization: ${response.statusText}`);
    }
    
    return response.json();
  }

  // 批量更新组织
  async batchUpdateOrganizations(updates: { id: string; data: Partial<Organization> }[]): Promise<ApiResponse<Organization[]>> {
    const response = await fetch(`${this.baseUrl}/batch`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ updates }),
    });
    
    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}));
      throw new Error(errorData.message || `Failed to batch update organizations: ${response.statusText}`);
    }
    
    return response.json();
  }

  // 导出组织架构
  async exportOrganizations(tenantId?: string): Promise<Blob> {
    const searchParams = new URLSearchParams();
    if (tenantId) {
      searchParams.append('tenantId', tenantId);
    }

    const response = await fetch(`${this.baseUrl}/export?${searchParams.toString()}`);
    if (!response.ok) {
      throw new Error(`Failed to export organizations: ${response.statusText}`);
    }
    
    return response.blob();
  }

  // 导入组织架构
  async importOrganizations(file: File, tenantId?: string): Promise<ApiResponse<{ success: number; failed: number; errors: string[] }>> {
    const formData = new FormData();
    formData.append('file', file);
    if (tenantId) {
      formData.append('tenantId', tenantId);
    }

    const response = await fetch(`${this.baseUrl}/import`, {
      method: 'POST',
      body: formData,
    });
    
    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}));
      throw new Error(errorData.message || `Failed to import organizations: ${response.statusText}`);
    }
    
    return response.json();
  }
}

// 导出单例实例
export const organizationService = new OrganizationService();
export default organizationService;